<template>
  <div class="page-container">
    <div class="card-title" v-show="showSearch">
      <el-form size="small" label-width="68px" :model="queryParams" ref="queryForm">
        <el-row :gutter="48">
          <el-col :md="6" :sm="24">
            <el-form-item label="表格名称">
              <el-input v-model="queryParams.tableName" class="search-item" placeholder="请输入表格名称" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :md="6" :sm="24">
            <el-form-item label="表格描述">
              <el-input v-model="queryParams.tableComment" class="search-item" placeholder="请输入表格描述" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :md="6" :sm="24">
            <!-- 创建时间 -->
            <el-form-item label="创建时间">
              <el-date-picker
                v-model="queryParams.dataRange"
                class="search-item"
                value-format="yyyy-MM-dd"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <div class="search-content">
            <el-form-item class="search-button">
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="handleReset">重置</el-button>
              <el-button
                type="text"
                :icon="advanced ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"
                class="advanced-button"
                @click="toggleAdvanced">
                {{ advanced ? '关闭' : '展开' }}
              </el-button>
            </el-form-item>
          </div>
        </el-row>
      </el-form>
    </div>
    <div class="card">
      <el-row :gutter="10" class="button-container">
        <el-col :span="1.5">
          <el-button type="primary" icon="el-icon-s-order" size="mini" plain @click="gotoGenerateLog">生成历史</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" :columns="columns" @getTableData="getTableData"></right-toolbar>
      </el-row>

      <el-table v-loading="loading" element-loading-text="正在加载表格数据" :data="tableData" border>
        <template slot="empty">
          <el-empty :image-size="200"></el-empty>
        </template>
        <!-- 表格名称 -->
        <el-table-column prop="tableName" label="表格名称" align="center" v-if="columns[0].visible" show-overflow-tooltip></el-table-column>
        <!-- 表格描述 -->
        <el-table-column prop="tableComment" label="表格描述" align="center" v-if="columns[1].visible" show-overflow-tooltip></el-table-column>
        <!-- 登录时间 -->
        <el-table-column prop="createTime" label="创建时间" align="center" v-if="columns[2].visible">
          <template slot-scope="scope">
            <span>{{ scope.row.createTime | dateFilter }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作"  align="center">
          <template slot-scope="scope">
            <el-button type="text" size="small" icon="el-icon-view" @click="handleView(scope.row)">预览</el-button>
            <el-button type="text" size="small" icon="el-icon-download" @click="handleDownload(scope.row)">生成</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页器 -->
      <pagination
        :background="false"
        :total="total"
        :page.sync="queryParams.currentPage"
        :limit.sync="queryParams.pageSize"
        @pagination="getTableData"
      />
    </div>

    <!-- 配置界面 -->
    <el-dialog title="代码生成配置" :visible="configVisible" width="600px" :before-close="handleConfigClose">
      <div class="config-wrapper" v-loading="configLoading" element-loading-text="正在加载代码生成配置信息">
        <el-form ref="configForm" :model="formData" :rules="rules" label-width="100px" label-position="right" size="small">
          <el-row :gutter="20" class="form-row">
            <el-col :span="12">
              <el-form-item label="模块名称" prop="moduleName">
                <el-input v-model="formData.moduleName" placeholder="请输入模块名称" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="包名称" prop="packageName">
                <el-input v-model="formData.packageName" placeholder="请输入包名称" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="enableChain">
                <span slot="label">
                  <el-tooltip content="选择是否开启链式编程" placement="top">
                  <i class="el-icon-question"></i>
                  </el-tooltip>
                  链式编程
                </span>
                <el-radio-group v-model="formData.enableChain">
                  <el-radio :label="false">不开启</el-radio>
                  <el-radio :label="true">开启</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="enableCache">
                <span slot="label">
                  <el-tooltip content="选择是否开启二级缓存" placement="top">
                  <i class="el-icon-question"></i>
                  </el-tooltip>
                  二级缓存
                </span>
                <el-radio-group v-model="formData.enableCache">
                  <el-radio :label="false">不开启</el-radio>
                  <el-radio :label="true">开启</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div slot="footer">
        <!-- :loading="buttonLoading" -->
        <el-button
          type="danger"
          @click="handleClearConfig()"
          size="small"
          icon="el-icon-error">
          取消
        </el-button>
        <el-button
          type="primary"
          size="small"
          @click="handleConfirm()"
          icon="el-icon-success">
          确定
        </el-button>
      </div>
    </el-dialog>

    <!-- 预览界面 -->
    <el-dialog :title="preview.title" :visible.sync="preview.open" width="70%" top="5vh" append-to-body :close-on-press-escape="false" :close-on-click-modal="false" class="scrollbar">
      <div class="preview-wrapper">
        <el-tabs v-model="preview.activeName">
          <el-tab-pane v-for="(value, key) in preview.data" :label="key" :name="key" :key="key">
            <el-link :underline="false" icon="el-icon-document-copy" v-clipboard:copy="value" v-clipboard:success="clipboardSuccess" style="float:right">复制</el-link>
            <pre class="pre-wrapper">
              <code class="hljs" v-html="highlightedCode(value, key)"></code>
            </pre>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-dialog>

  </div>
</template>
<script>
import Pagination from '../../../components/Pagination/index'
import RightToolbar from '../../../components/RightToolbar/index'
import { listTables, preview, download } from '../../../api/webiste/generate'
import { saveAs } from 'file-saver'
import hljs from 'highlight.js'
import 'highlight.js/styles/github.css'
hljs.registerLanguage('java', require('highlight.js/lib/languages/java'))
hljs.registerLanguage('xml', require('highlight.js/lib/languages/xml'))
hljs.registerLanguage('html', require('highlight.js/lib/languages/xml'))
hljs.registerLanguage('vue', require('highlight.js/lib/languages/xml'))
hljs.registerLanguage('javascript', require('highlight.js/lib/languages/javascript'))
hljs.registerLanguage('sql', require('highlight.js/lib/languages/sql'))

export default {
  name: 'Generator',

  components: { Pagination, RightToolbar },

  data () {
    return {
      // 高级搜索 展开/关闭
      advanced: false,
      // 是否展示搜索内容
      showSearch: true,
      // 数据总条数
      total: 0,
      // 数据表格等待框
      loading: false,
      // 查询参数
      queryParams: {
        // 页数
        currentPage: 1,
        // 页面大小
        pageSize: 10,
        // 表格名称
        tableName: undefined,
        // 表格描述
        tableComment: undefined,
        // 时间范围
        dataRange: []
      },
      // 代码生成配置信息表单对象
      formData: {
        // 表名
        tableName: undefined,
        // 模块名
        moduleName: undefined,
        // 包名
        packageName: undefined,
        // 链式编程
        enableChain: false,
        // 二级缓存
        enableCache: false
      },
      // 代码生成配置信息表单校验规则
      rules: {
        // 模块名
        moduleName: [{ required: true, message: '模块名称不能为空', trigger: 'blur' }],
        // 包名
        packageName: [{ required: true, message: '包名不能为空', trigger: 'blur' }]
      },
      // 用户登录信息对话框等待框
      loginLogLoading: false,
      // 对话框按钮等待框
      buttonLoading: false,
      // 列信息
      columns: [
        // 日志编号
        { key: 0, label: '表格名称', visible: true },
        // 登录用户名称
        { key: 1, label: '表注释', visible: true },
        // 登录IP
        { key: 2, label: '创建时间', visible: true }
      ],
      // 表格数据
      tableData: [],
      // 预览参数
      preview: {
        open: false,
        title: '代码预览',
        data: {},
        activeName: 'domain.java'
      },
      // 代码配置界面
      configVisible: false,
      // 代码生成等待框
      configLoading: false,
      // 当前操作类型
      operateType: undefined
    }
  },

  mounted () {
    // 查询表格数据
    this.getTableData()
  },

  methods: {
    // 获取表格数据
    getTableData () {
      // 开启加载框
      this.loading = true
      listTables(this.queryParams).then((res) => {
        // 赋值数据参数
        this.tableData = res.list
        this.total = res.total
        // 关闭等待框
        this.loading = false
      }).catch(() => {
        // 关闭等待框
        this.loading = false
      })
    },
    toggleAdvanced () {
      this.advanced = !this.advanced
    },
    // 点击查询按钮
    handleQuery () {
      this.queryParams.currentPage = 1
      this.getTableData()
    },
    // 点击重置按钮
    handleReset () {
      // 表名
      this.queryParams.tableName = ''
      // 表格描述
      this.queryParams.tableComment = ''
      // 创建时间
      this.queryParams.dataRange = []
    },
    // 预览代码
    handleView (row) {
      const that = this
      that.operateType = 'view'
      if (that.formData.tableName && that.formData.tableName !== row.tableName) {
        that.handleClearConfig()
      }
      // 更新当前表格配置
      that.formData.tableName = row.tableName
      // 如果配置没有完成则不能打开代码预览
      if (!that.formData.moduleName || !that.formData.packageName) {
        that.configVisible = true
        return
      }
      preview(that.formData).then((res) => {
        that.preview.data = res
        that.preview.activeName = 'domain.java'
        // 打开代码预览框
        that.preview.open = true
      })
    },
    // 高亮显示代码
    highlightedCode (code, key) {
      // 根据文件名称截取语言
      var language = key.substring(key.indexOf('.') + 1, key.length)
      const result = hljs.highlight(language, code || '', true)
      return result.value || '&nbsp;'
    },
    // 关闭代码生成配置框
    handleConfigClose () {
      this.configVisible = false
    },
    // 关闭代码生成配置对话框并清除配置规则
    handleClearConfig () {
      this.handleConfigClose()
      this.formData = {
        // 表名
        tableName: undefined,
        // 模块名
        moduleName: undefined,
        // 包名
        packageName: undefined,
        // 链式编程
        enableChain: false,
        // 二级缓存
        enableCache: false
      }
      this.operateType = undefined
      // 清除表单校验规则
      this.resetForm('configForm')
    },
    // 点击确认
    handleConfirm () {
      const that = this
      // 关闭配置对话框
      this.$refs.configForm.validate(valid => {
        // 校验未通过则直接返回
        if (!valid) return
        that.handleConfigClose()
        if (that.operateType === 'view') {
          that.handleView(that.formData)
        }
        if (that.operateType === 'download') {
          that.handleDownload(that.formData)
        }
      })
    },
    // 复制代码成功
    clipboardSuccess () {
      this.$message.success('复制成功')
    },
    // 预览代码
    handleDownload (row) {
      const that = this
      that.operateType = 'download'
      if (that.formData.tableName && that.formData.tableName !== row.tableName) {
        that.handleClearConfig()
      }
      // 更新当前表格配置
      that.formData.tableName = row.tableName
      // 如果配置没有完成则不能打开代码预览
      if (!that.formData.moduleName || !that.formData.packageName) {
        that.configVisible = true
        return
      }
      download(that.formData).then((res) => {
        const blob = new Blob([res], { type: 'application/zip' })
        saveAs(blob, 'blog.zip')
      })
    },
    // 跳转到代码生成历史
    gotoGenerateLog () {
      this.$router.push('/system-content/generate-log')
    }
  }
}

</script>

<style lang="scss" scoped>
.config-wrapper {
  padding: 10px 30px;
}
.preview-wrapper {
  padding: 10px;
}
.form-row {
  display:flex;
  flex-wrap: wrap;
}
.pre-wrapper {
  margin: 0;
}
.hljs {
  padding: 0;
}
</style>
